package module.project
{
	import adobe.crypto.MD5;
	import drongo.desktop.utils.StringUtil;
	import drongo.desktop.utils.UtilsFile;
	import drongo.desktop.utils.UtilsStr;
	import drongo.desktop.window.WindowManager;
	
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.net.FileFilter;
	import flash.net.SharedObject;
	import flash.system.Capabilities;
	import flash.utils.ByteArray;
	
	import common.WindowKeys;
	import common.view.FGUIMediator;
	import common.window.AlertDialog;
	
	import fairygui.GButton;
	
	import ui.Builder.UI_OpenProjectWindow;
	
	/**
	 * 工程
	 */
	public class ProjectMediator extends FGUIMediator
	{
		[Inject]
		public var view:UI_OpenProjectWindow;
		
		private var cookie:SharedObject
		
		/**
		 * 工程文件后缀
		 */
		private var PROJECT_FILE_EXTS:Array=["project"];
		
		public function ProjectMediator()
		{
			super();
			cookie=SharedObject.getLocal("JGameEditor");
		}
		
		override public function initialize():void
		{
			super.initialize();
			view.m_btnOpen.addClickListener(this.OpenButtonClick);
			view.m_btnOpenOther.addClickListener(this.OpenOtherButtonClick);
			view.m_btnOpenFolder.addClickListener(this.OpenFolderButtonClick);
			view.m_btnCreate.addClickListener(this.CreateButtonClick);
			view.m_btnBrowse.addClickListener(this.BrowseButtonClick);
			view.m_btnDelete.addClickListener(this.DeleteButtonClick);
			
			this.ReadByLocal();
		}
		
		private function OpenButtonClick(e:Event):void{
			var nativePath:String = String(this.view.m_list.getChildAt(this.view.m_list.selectedIndex).data);
			this.openProject(nativePath);
		}
		
		private function OpenOtherButtonClick(e:Event):void{
			UtilsFile.browseForOpen("打开项目",[new FileFilter("地图项目","*.project")],function(file:File):void
			{
				openProject(file.nativePath);
			});
		}
		
		private function OpenFolderButtonClick(e:Event):void
		{
			UtilsFile.browseForDirectory("打开项目",function(file:File):void
			{
				openProject(file.nativePath);
			});
		}
		
		private function CreateButtonClick(e:Event):void{
			var name:String = UtilsStr.validateName( view.m_projectName.text);
			var path:String = view.m_path.text;
			if(StringUtil.IsEmpty(path)){
				AlertDialog.open(this.view.root,"路径不能为空!");
				return;
			}
			var projectConfig:String=JSON.stringify({
				id:MD5.hash(path + new Date().time + Math.random() * 10000 + name + Capabilities.serverString),
				version: "0.1"
			},null," ");
			var byte:ByteArray=new ByteArray();
			byte.writeUTFBytes(projectConfig);
			//保存工程
			var projectFile:File=new File(path + File.separator + name + ".project");
			if(projectFile.exists){
				AlertDialog.open(this.view.root,"项目已存在！");
				return;
			}
			UtilsFile.saveBytes(projectFile,byte);
			
			//地图存放目录
			new File(path+File.separator+"maps").createDirectory();
			
			var settingsDirFile:File = new File(path + File.separator +"settings");
			settingsDirFile.createDirectory();
			//复制设置模板到项目
			UtilsFile.copyFile(new File(File.applicationDirectory.nativePath+File.separator+"res/configs/settings.json"),new File(settingsDirFile.nativePath+File.separator+"settings.json"));
			
			//打开工程
			openProject(new File(this.view.m_path.text).nativePath);
		}
		
		private function BrowseButtonClick(e:Event):void{
			UtilsFile.browseForDirectory("选择项目路径",function(file:File):void
			{
				view.m_path.text = file.nativePath;
			});
		}
		
		private function DeleteButtonClick(e:Event):void{
			var selectIndex:int = this.view.m_list.selectedIndex;
			var item:GButton = this.view.m_list.getChildAt(selectIndex) as GButton;
			var selectStr:String = String(item.data);
			var recentList:Array = this.cookie.data.recent_project;
			if(!recentList)
			{
				recentList = [];
			}
			var index:int = recentList.indexOf(selectStr);
			if(index != -1)
				recentList.splice(index - 1,2);
			
			this.cookie.data.recent_project = recentList;
			this.cookie.setDirty("recent_project");
			this.view.m_list.removeChildToPoolAt(selectIndex);
			if(selectIndex >= 1)
				this.view.m_list.selectedIndex = selectIndex - 1;
			else
				this.view.m_list.selectedIndex = 0;
			
			this.view.m_btnOpen.enabled = this.view.m_list.numChildren > 0;
			this.view.m_btnDelete.enabled = this.view.m_list.numChildren > 0;
		}
		
		/**
		 * 打开工程
		 * @param nativePath
		 */
		private function openProject(nativePath:String):void
		{
			var file:File = new File(nativePath);
			if(!file.exists)
			{
				AlertDialog.open(this.view.root,"项目路径不存在");
				return;
			}
			
			//工程文件 .dg文件
			var projectDescFile:File;
			if(file.isDirectory)
			{
				//是目录搜索出工程文件
				var files:Array = file.getDirectoryListing();
				for each (var item:File in files) 
				{
					if(PROJECT_FILE_EXTS.indexOf(item.extension) != -1)
					{
						projectDescFile = item;
						break;
					}
				}
			}
			else 
			{
				projectDescFile = file;
			}
			
			//添加记录
			AddRecent(projectDescFile.parent.nativePath,projectDescFile.name.replace(".project",""));
			
			WindowManager.call(WindowKeys.MAP,projectDescFile);
			
			//关闭
			view.displayObject.stage.nativeWindow.close();
		}
		
		private function ReadByLocal():void{

			//设置工程列表
			var recentList:Array = cookie.data.recent_project;
			if(!recentList)
				recentList = [];
			
			if(recentList.length % 2 != 0)
			{
				recentList.length = 0;
				delete cookie.data.recent_project;
			}
			
			var rl:int = recentList.length / 2;
			this.view.m_list.removeChildrenToPool();
			var i:int = rl - 1;
			while(i >= 0)
			{
				var path:String = recentList[i * 2 + 1];
				try
				{
					if(!new File(path).exists)
					{
						i--;
						continue;
					}
				}
				catch(err:Error)
				{
					i--;
					continue;
				}
				var item:GButton = this.view.m_list.addItemFromPool().asButton;
				item.title = recentList[i * 2] + "	:	" + path;
				item.data = path;
				i--;
			}
			this.view.m_list.selectedIndex = 0;
		}
		
		/**
		 * 添加到最近工程 
		 */
		private function AddRecent(basePath:String,name:String):void
		{
			var recentList:Array = this.cookie.data.recent_project;
			if(!recentList)
				recentList = [];
			
			if(recentList.length % 2 != 0)
			{
				recentList.length = 0;
				delete this.cookie.data.recent_project;
			}
			
			//判断已经在最近列表就删除
			var index:int = recentList.indexOf(basePath);
			if(index != -1)
				recentList.splice(index - 1,2);
			
			recentList.push(name,basePath);
			this.cookie.data.recent_project = recentList;
			this.cookie.setDirty("recent_project");
		}
		
		override public function destroy():void{
			super.destroy();
			this.view=null;
			this.cookie=null;
		}
	}
}